package com.dream.house.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.servyou.utils.CoreUtils;
import cn.com.servyou.utils.Page;

import com.dream.house.entity.GroupDTO;
import com.dream.house.entity.UserDTO;
import com.dream.house.service.DocumentService;
import com.dream.house.service.UserService;
import com.dream.house.utils.Constants;

@Controller
public class LoginController {
	private static Logger log=Logger.getLogger(LoginController.class);
	
	@Autowired
	UserService service;
	@Autowired
	DocumentService docService;
	
	@RequestMapping("index")
	public String index(HttpServletRequest request,HttpSession session, Model model) {
		//访问首页时清除session,类似退出
		session.removeAttribute(Constants.CURRENT_USER);
		
		List<GroupDTO> groups=service.getGroups(null);
		
		model.addAttribute("groups", groups);
		
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("doc_type", "0");//0-通知，1-公告
		Page notice=docService.findByPage(map, 1, 5);
		map.put("doc_type", "1");//0-通知，1-公告
		Page bullition=docService.findByPage(map, 1, 5);
		
		model.addAttribute("notice", notice);
		model.addAttribute("bullition", bullition);
		
		return "index";
	}
	
	@RequestMapping("login")
	public String login(HttpServletRequest request, Model model) {
		String userId = request.getParameter("user_id");
		String password = request.getParameter("password");
		String groupId= request.getParameter("group_id");
		
		if (CoreUtils.strIsNull(userId) || CoreUtils.strIsNull(password) || CoreUtils.strIsNull(groupId)) {
			log.warn("用户名或密码为空,不予进行登录操作....");
			return "";
		}
		UserDTO user=service.getUser(userId,groupId);
		
		if(user.getPass().equals(password)){
			//放入session
			request.getSession().setAttribute(Constants.CURRENT_USER, user);
			
			return "build/index";
		}
		
		return "";
	}
	
    @RequestMapping("dispather")
    public String dispather(Model model, String flag) {
        if ("topframe".equals(flag)) {
            return "admin/topframe";
        } else if ("leftframe".equals(flag)) {
            return "admin/leftframe";
        } else if ("welcome".equals(flag)) {
            return "admin/welcome";
        }
        return "";
    }
    
    @RequestMapping("heading")
	public String heading() {
		return "heading";
	}
    
    @RequestMapping("tree")
	public String tree() {
		return "tree";
	}
    
    @RequestMapping("gotoLogin")
    public String gotoLogin() {
		return "login";
	}

}
